//
//  ArtBuyViewController.m
//  EasyToo
//
//  Created by Jr Lan on 13-9-1.
//
//

#import "ArtBuyViewController.h"
#import "ArtConfirmViewController.h"
#import "NetworkAlertView.h"
#import <QuartzCore/QuartzCore.h>

@interface ArtBuyViewController ()

@end

@implementation ArtBuyViewController
{
    UITextField *_countTF;
    UITextField *_phoneTF;
    
    UIButton *_zfbButton;
    UIButton *_ybButton;
    
    NSInteger _payType;
    
    UITextField *_priceTF;
    UIPickerView *_pricePicker;
    NSMutableArray *_priceArray;
    
    UITextField *_addressTF;
    UIAlertView *_baseAlert;
}

- (void)dealloc
{
    [_countTF release];
    [_phoneTF release];
    [_zfbButton release];
    [_ybButton release];
    [_priceTF release];
    [_pricePicker release];
    [_priceArray release];
    [_addressTF release];
    
    _countTF = nil;
    _phoneTF = nil;
    _zfbButton = nil;
    _ybButton = nil;
    _priceTF = nil;
    _pricePicker = nil;
    _priceArray = nil;
    _addressTF = nil;
    
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    //初始化视图
    [self init_view];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//初始化视图
- (void)init_view
{
    self.title = @"演艺票";
    //加载背影
     [self.view setBackgroundColor:BackgroundColor];
    
    int width = [DeviceUtil getScreenWidth];
    int heigth = self.view.frame.size.height;
    
    UIScrollView *myscrollview = [[[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, width, heigth)]autorelease];
    myscrollview.directionalLockEnabled = YES; //只能一个方向滑动
    myscrollview.pagingEnabled = NO; //是否翻页
    myscrollview.backgroundColor = [UIColor whiteColor];
    myscrollview.showsVerticalScrollIndicator =YES; //垂直方向的滚动指示
    myscrollview.indicatorStyle = UIScrollViewIndicatorStyleWhite;//滚动指示的风格
    myscrollview.showsHorizontalScrollIndicator = NO;//水平方向的滚动指示
    myscrollview.delegate = self;
    CGSize newSize = CGSizeMake(width, 1500);
    [myscrollview setContentSize:newSize];
    
    UIControl *control = [[[UIControl alloc] initWithFrame:myscrollview.frame] autorelease];
    [myscrollview addSubview:control];
    [control addTarget:self action:@selector(onBackgroudTouch) forControlEvents:UIControlEventTouchDown];

    
    //加载票务信息
    [self initTicket:myscrollview];
    
    //选择价格
    [self init_price:myscrollview];
    
    //手机号码
    _phoneTF = [[UITextField alloc] initWithFrame:CGRectMake(20, 200, 280, 50)];
    _phoneTF.text = @"";
    _phoneTF.placeholder = @"请输入手机号码";
    _phoneTF.keyboardType = UIKeyboardTypeNumberPad;
    _phoneTF.font = [UIFont fontWithName:@"Arial" size:18.0f];
    _phoneTF.textColor = [UIColor blackColor];
    _phoneTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _phoneTF.borderStyle = UITextBorderStyleRoundedRect;
    _phoneTF.delegate = self ;
    _phoneTF.returnKeyType =UIReturnKeyDone;
    _phoneTF.layer.borderColor = [UIColor grayColor].CGColor;
    _phoneTF.layer.borderWidth = 1 ;
    _phoneTF.layer.cornerRadius = 10 ;
    [myscrollview addSubview:_phoneTF];
    
    //描述
    UILabel *phonedesclbl = [[[UILabel alloc]initWithFrame:CGRectMake(10, 260, 300, 30)]autorelease];
    phonedesclbl.text = @"请确定手机号码无误，支付成功后将无法修改";
    phonedesclbl.font = [UIFont systemFontOfSize:15];
    phonedesclbl.textColor = [UIColor lightGrayColor];
    phonedesclbl.backgroundColor = [UIColor clearColor];
    phonedesclbl.adjustsFontSizeToFitWidth = YES;
    [myscrollview addSubview:phonedesclbl];
    
    //地址
    _addressTF = [[UITextField alloc] initWithFrame:CGRectMake(20, 300, 280, 50)];
    _addressTF.text = @"";
    _addressTF.placeholder = @"配送地址（仅限广州地区）";
    _addressTF.font = [UIFont fontWithName:@"Arial" size:18.0f];
    _addressTF.textColor = [UIColor blackColor];
    _addressTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _addressTF.borderStyle = UITextBorderStyleRoundedRect;
    _addressTF.delegate = self ;
    _addressTF.returnKeyType =UIReturnKeyDone;
    _addressTF.layer.borderColor = [UIColor grayColor].CGColor;
    _addressTF.layer.borderWidth = 1 ;
    _addressTF.layer.cornerRadius = 10 ;
    [myscrollview addSubview:_addressTF];
    
    UILabel *label_pay = [[[UILabel alloc]initWithFrame:CGRectMake(10, 360, 180, 30)]autorelease];
    label_pay.backgroundColor = [UIColor clearColor];
    label_pay.text = @"选择支付方式:";
    [myscrollview addSubview:label_pay];
    
//    _zfbButton = [[UIButton alloc] initWithFrame:CGRectMake(30, 400, 100, 30)];
//    [_zfbButton setBackgroundImage:[UIImage imageNamed:@"zfb.png"] forState:UIControlStateNormal];
//    [_zfbButton setBackgroundImage:[UIImage imageNamed:@"zhifubao2.png"] forState:UIControlStateSelected];
//    [_zfbButton addTarget:self action:@selector(zfbButtonPick:) forControlEvents:UIControlEventTouchDown];
//    [myscrollview addSubview:_zfbButton];
    
    _ybButton = [[UIButton alloc] initWithFrame:CGRectMake(30, 400, 100, 30)];
    [_ybButton setBackgroundImage:[UIImage imageNamed:@"yinlian1"] forState:UIControlStateNormal];
    [_ybButton setBackgroundImage:[UIImage imageNamed:@"yinlian2"] forState:UIControlStateSelected];
    [_ybButton addTarget:self action:@selector(ybButtonPick:) forControlEvents:UIControlEventTouchDown];
    [myscrollview addSubview:_ybButton];
    
    
    UIButton *nextStep =[UIButton buttonWithType:UIButtonTypeCustom];
    nextStep.frame = CGRectMake(40, 440, 230, 40);
    [nextStep setBackgroundImage:[UIImage imageNamed:@"xyb"] forState:UIControlStateNormal];
    [nextStep setTitle:@"下一步" forState:UIControlStateNormal];
    nextStep.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    nextStep.layer.borderColor = [UIColor grayColor].CGColor;
    nextStep.layer.borderWidth = 1 ;
    nextStep.layer.cornerRadius = 10 ;
    [myscrollview addSubview:nextStep];
    [nextStep addTarget:self action:@selector(confirmMessge) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:myscrollview];
}

//加载票务信息
- (void) initTicket:(UIScrollView*)myscrollview
{
    //加载图片
    UIImageView *imgView = [[[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 300, 130)]autorelease];
    imgView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    imgView.image = [UIImage imageNamed:@"actingtickets_03"];
    [myscrollview addSubview:imgView];
    
    //加载说明
    UILabel *desclbl = [[[UILabel alloc]initWithFrame:CGRectMake(40, 10, 280, 30)]autorelease];
    desclbl.text = @"确认信息";
    desclbl.font = [UIFont systemFontOfSize:20];
    desclbl.textColor = [UIColor redColor];
    desclbl.backgroundColor = [UIColor clearColor];
    desclbl.adjustsFontSizeToFitWidth = YES;
    desclbl.textAlignment = NSTextAlignmentCenter;
    [myscrollview addSubview:desclbl];
    
    //加载说明
    UILabel *titlenameclbl = [[[UILabel alloc]initWithFrame:CGRectMake(40, 40, 280, 30)]autorelease];
    titlenameclbl.text = self.artInfo.ProjectName;
    titlenameclbl.font = [UIFont systemFontOfSize:15];
    titlenameclbl.backgroundColor = [UIColor clearColor];
    titlenameclbl.adjustsFontSizeToFitWidth = YES;
    [myscrollview addSubview:titlenameclbl];
    
    //加载日期
    UILabel *timelbl = [[[UILabel alloc]initWithFrame:CGRectMake(40, 70, 280, 30)]autorelease];
    timelbl.text = self.artInfo.PerformTime;
    timelbl.font = [UIFont systemFontOfSize:15];
    timelbl.backgroundColor = [UIColor clearColor];
    timelbl.adjustsFontSizeToFitWidth = YES;
    timelbl.textAlignment = NSTextAlignmentLeft;
    [myscrollview addSubview:timelbl];
    
    //加载数量
    UILabel *countlbl = [[[UILabel alloc]initWithFrame:CGRectMake(40, 100, 40, 30)]autorelease];
    countlbl.text = @"数量：";
    countlbl.font = [UIFont systemFontOfSize:20];
    countlbl.backgroundColor = [UIColor clearColor];
    countlbl.adjustsFontSizeToFitWidth = YES;
    countlbl.textAlignment = NSTextAlignmentCenter;
    [myscrollview addSubview:countlbl];
    
    //加载加号
    UIButton *plusbtn =[UIButton buttonWithType:UIButtonTypeCustom];
    plusbtn.frame = CGRectMake(90, 102, 30, 25);
    [plusbtn setBackgroundImage:[UIImage imageNamed:@"15.png"] forState:UIControlStateNormal];
    [myscrollview addSubview:plusbtn];
    [plusbtn addTarget:self action:@selector(plusEvent) forControlEvents:UIControlEventTouchUpInside];
    
    //加载数量
    _countTF = [[UITextField alloc] initWithFrame:CGRectMake(130, 102, 40, 25)];
    _countTF.text = @"2";
    [_countTF setBorderStyle:UITextBorderStyleBezel];
    _countTF.backgroundColor = [UIColor whiteColor];
    [_countTF setEnabled:NO];
    [myscrollview addSubview:_countTF];
    
    //加载减号
    UIButton *minusbtn =[UIButton buttonWithType:UIButtonTypeCustom];
    minusbtn.frame = CGRectMake(180, 102, 30, 25);
    [minusbtn setBackgroundImage:[UIImage imageNamed:@"16.png"] forState:UIControlStateNormal];
    [myscrollview addSubview:minusbtn];
    [minusbtn addTarget:self action:@selector(minusEvent) forControlEvents:UIControlEventTouchUpInside];
}

//价格
- (void) init_price:(UIScrollView*)myscrollview
{
    _priceTF = [[UITextField alloc] initWithFrame:CGRectMake(20, 140, 280, 50)];
    _priceTF.text = @"";
    _priceTF.placeholder = @"选择价格";
    _priceTF.font = [UIFont fontWithName:@"Arial" size:18.0f];
    _priceTF.textColor = [UIColor blackColor];
    _priceTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _priceTF.borderStyle = UITextBorderStyleRoundedRect;
    _priceTF.delegate = self ;
    _priceTF.returnKeyType =UIReturnKeyDone;
    _priceTF.layer.borderColor = [UIColor grayColor].CGColor;
    _priceTF.layer.borderWidth = 1 ;
    _priceTF.layer.cornerRadius = 10 ;
    [myscrollview addSubview:_priceTF];
    
    // 建立 UIToolbar
    UIToolbar *_toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
    UIBarButtonItem *_right = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(cancelstartPicker)];
    
    // 把按鈕加進 UIToolbar
    _toolBar.items = [NSArray arrayWithObject:_right];
    
    _priceArray = [[NSMutableArray alloc]init];
    for (int i = 0; i < [self.artInfo.priceInfoArray count]; i++) {
        PriceInfo *priceInfo = [self.artInfo.priceInfoArray objectAtIndex:i];
        [_priceArray addObject:[NSString stringWithFormat:@"%@元", priceInfo.Price]];
    }
    _pricePicker = [[UIPickerView alloc]initWithFrame:CGRectZero];
    _pricePicker.showsSelectionIndicator = YES;
    
    _priceTF.inputAccessoryView = _toolBar;
    _priceTF.delegate = self;
    _pricePicker.delegate = self;
    _pricePicker.dataSource = self;
    _pricePicker.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    _priceTF.inputView = _pricePicker;

}

//数量增加
- (void)plusEvent
{
    _countTF.text = [NSString stringWithFormat:@"%d", ([_countTF.text intValue] + 1)];
}

//数量减少
- (void)minusEvent
{
    int count = [_countTF.text intValue];
    if (count > 0) {
        _countTF.text = [NSString stringWithFormat:@"%d", (count - 1)];
    }
}

-(void)zfbButtonPick:(id)sender
{
    [_zfbButton setSelected:YES];
    [_ybButton setSelected:NO];
    _payType = 0;
}

-(void)ybButtonPick:(id)sender
{
    [_zfbButton setSelected:NO];
    [_ybButton setSelected:YES];
    _payType = 1;
}

-(void)confirmMessge
{
    if ([_countTF.text isEqualToString:@"0"]) {
        _baseAlert = [[UIAlertView alloc]  initWithTitle:@"请选择数量" message:@"票数不能为0哦亲"  delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles: nil];
        [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
        [_baseAlert show];
        
    } else if([_priceTF.text isEqualToString:@""] || [_phoneTF.text isEqualToString:@""] || [_addressTF.text isEqualToString:@""]){
        _baseAlert = [[UIAlertView alloc]  initWithTitle:@"数据不完整" message:@"请填写完整的数据"  delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles: nil];
        [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
        [_baseAlert show];
        
        //判断手机号码格式
    }else if ([DeviceUtil isMobileNumber:_phoneTF.text] == NO) {
        _baseAlert = [[UIAlertView alloc]  initWithTitle:@"手机填错了" message:@"手机号格式出错"  delegate:self cancelButtonTitle:@"返回" otherButtonTitles: nil];
        [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
        [_baseAlert show];
        
    } else{
        ArtManager *artmanager = [ArtManager shareManager];
        artmanager.delegate = self;
        
        PriceInfo *priceInfo;
        for (int i = 0; i < [self.artInfo.priceInfoArray count]; i++) {
            PriceInfo *tempInfo =  [self.artInfo.priceInfoArray objectAtIndex:i];
            if ([[NSString stringWithFormat:@"%@元", tempInfo.Price] isEqualToString:_priceTF.text]) {
                priceInfo = tempInfo;
            }
        }
        
        int buyamount = [_countTF.text intValue];
        int maxamount = [priceInfo.Quantity intValue];
        if (buyamount > maxamount) {
            UIAlertView* baseAlert = [[[UIAlertView alloc] initWithTitle:@"购买太多了" message:nil delegate:self cancelButtonTitle:@"购买个数超过系统最大限制数" otherButtonTitles: nil] autorelease];
            [baseAlert show];
        } else {
            [[NetworkAlertView shareView] showNetView];
            [artmanager buyArtInfo:[NSString stringWithFormat:@"%d", buyamount]
                       singlePrice:priceInfo.Price
                            mobile:_phoneTF.text
                      customerName:_phoneTF.text
                           priceId:priceInfo.PGradePriceID];
        }
        
    }
    
}

//购买门票
- (void)buyArtInfo:(BOOL)isSuccess OrderId:(NSString*)OrderId SumPrice:(NSString*)SumPrice
{
    [[NetworkAlertView shareView] delView];
    if (isSuccess) {
        ArtConfirmViewController *confirmController = [[ArtConfirmViewController alloc]init];
        confirmController.artInfo = self.artInfo;
        confirmController.count = _countTF.text;
        confirmController.cash = _priceTF.text;
        confirmController.phone = _phoneTF.text;
        confirmController.address = _addressTF.text;
        confirmController.type = _payType;
        confirmController.OrderId = OrderId;
        confirmController.SumPrice = SumPrice;
        confirmController.amount = _countTF.text;
        [self.navigationController pushViewController:confirmController animated:YES];
        [confirmController release];
    } else {
        UIAlertView* baseAlert = [[[UIAlertView alloc] initWithTitle:@"下单失败" message:nil delegate:self cancelButtonTitle:@"下单失败，请重新尝试，谢谢" otherButtonTitles: nil] autorelease];
        [baseAlert show];
    }
    
}


- (void) performDismiss: (NSTimer *)timer {
    [_baseAlert dismissWithClickedButtonIndex:0 animated:NO];//important
    [_baseAlert release];
    _baseAlert = NULL;
}

#pragma picker delegate
-(void) cancelstartPicker {
    [_priceTF endEditing:YES];
}

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}
-(NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return [_priceArray count];
}
-(NSString*) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    return [_priceArray objectAtIndex:row];
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[[UILabel alloc] init] autorelease];
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        [pickerLabel setFont:[UIFont systemFontOfSize:15]];
    }
    // Fill the label text here
    pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
}

-(void)textFieldDidEndEditing:(UITextField *)textField{
    NSInteger row = [_pricePicker selectedRowInComponent:0];
    _priceTF.text = [_priceArray objectAtIndex:row];
}

//开始编辑输入框的时候，软键盘出现，执行此事件
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    CGRect frame = textField.frame;
    int offset = frame.origin.y + 32 - (self.view.frame.size.height - 216.0);//键盘高度216
    
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    
    //将视图的Y坐标向上移动offset个单位，以使下面腾出地方用于软键盘的显示
    if(offset > 0)
        self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
    
    [UIView commitAnimations];
}


#pragma mark UITextFieldDelegate
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_phoneTF resignFirstResponder];
    [_addressTF resignFirstResponder];
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [_phoneTF resignFirstResponder];
    [_addressTF resignFirstResponder];
    return YES;
}

- (void)onBackgroudTouch
{
    [_phoneTF resignFirstResponder];
    [_addressTF resignFirstResponder];
}

@end




